<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/hexo/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/hexo/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/hexo/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/hexo/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/hexo/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/hexo/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/hexo/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="经验分享,">










<meta name="description" content="前些天，跟大家分享了一个socket的小工具，主要还是用来提高办公效率，今天在给大家分享一个基于WebSocket的聊天小程序（不是微信小程序哈哈），还是先简单介绍下WebSocket吧，尽管已经有很多大牛们在各种平台上介绍过它了，我还是想说点我自己的看法首先，什么是WebSocket？答案是：WebSocket 是一种网络通信协议，RFC6455 定义了它的通信标准， 是 HTML5 开始提供的">
<meta name="keywords" content="经验分享">
<meta property="og:type" content="article">
<meta property="og:title" content="一个基于WebSocket的聊天小程序">
<meta property="og:url" content="https://tony_df.coding.net/2018/10/29/一个基于websocket的聊天小程序/index.html">
<meta property="og:site_name" content="Tony&#39;s blog">
<meta property="og:description" content="前些天，跟大家分享了一个socket的小工具，主要还是用来提高办公效率，今天在给大家分享一个基于WebSocket的聊天小程序（不是微信小程序哈哈），还是先简单介绍下WebSocket吧，尽管已经有很多大牛们在各种平台上介绍过它了，我还是想说点我自己的看法首先，什么是WebSocket？答案是：WebSocket 是一种网络通信协议，RFC6455 定义了它的通信标准， 是 HTML5 开始提供的">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://tony_df.coding.net/2018/10/29/一个基于websocket的聊天小程序/coldwar.gif">
<meta property="og:image" content="https://tony_df.coding.net/2018/10/29/一个基于websocket的聊天小程序/websocket_data.png">
<meta property="og:image" content="https://tony_df.coding.net/2018/10/29/一个基于websocket的聊天小程序/connection.png">
<meta property="og:image" content="https://tony_df.coding.net/2018/10/29/一个基于websocket的聊天小程序/communication1.png">
<meta property="og:image" content="https://tony_df.coding.net/2018/10/29/一个基于websocket的聊天小程序/communication2.png">
<meta property="og:updated_time" content="2018-10-30T03:43:03.724Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="一个基于WebSocket的聊天小程序">
<meta name="twitter:description" content="前些天，跟大家分享了一个socket的小工具，主要还是用来提高办公效率，今天在给大家分享一个基于WebSocket的聊天小程序（不是微信小程序哈哈），还是先简单介绍下WebSocket吧，尽管已经有很多大牛们在各种平台上介绍过它了，我还是想说点我自己的看法首先，什么是WebSocket？答案是：WebSocket 是一种网络通信协议，RFC6455 定义了它的通信标准， 是 HTML5 开始提供的">
<meta name="twitter:image" content="https://tony_df.coding.net/2018/10/29/一个基于websocket的聊天小程序/coldwar.gif">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/hexo/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Tony'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://tony_df.coding.net/2018/10/29/一个基于websocket的聊天小程序/">





  <title>一个基于WebSocket的聊天小程序 | Tony's blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/hexo/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tony's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学着码代码,学着码人生;</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/hexo/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/hexo/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/hexo/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://tony_df.coding.net/hexo/2018/10/29/一个基于websocket的聊天小程序/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/hexo/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tony's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">一个基于WebSocket的聊天小程序</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-10-29T16:05:12+08:00">
                2018-10-29
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>前些天，跟大家分享了一个socket的小工具，主要还是用来提高办公效率，今天在给大家分享一个基于WebSocket的聊天小程序（不是微信小程序<del>哈哈），<br>还是先简单介绍下WebSocket吧，尽管已经有很多大牛们在各种平台上介绍过它了，我还是想说点我自己的看法<br>首先，什么是WebSocket？<br>答案是：WebSocket 是一种网络通信协议，RFC6455 定义了它的通信标准， 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。<br>靠，这不等于没说？什么叫全双工通信协议？<br>简单来说呢，全双工通信协议，顾名思义，就是我能给你说话的同时你也能跟我说话，咱俩平级，且可以插嘴</del>（就像电影《寒战2》里郭富城和梁家辉争吵一样，你一句我一句，俩人可以随便说），注意，是可以同时说哦，a-&gt;b,b-&gt;a<br><img src="coldwar.gif" alt="全双工"><br>此外，还有半双工通信<br>半双工通信，是指数据传输指可以在一个信号载体的两个方向上传输，但是不能同时传输，平级，但不能插嘴，你说完我再说~<br>那么还有一种单工通信<br>就是在只允许A向B传送信息，而B不能向A传送,（军人的命令就是服从<del>，不许反驳）<br>好了通讯说明白了，再来继续说WebSocket。<br>WebSocket应该说是顺应历史潮流诞生的一个东东，在没有WebSocket的时代，大家只得借助http协议来和服务器进行数据交互，HTTP 而协议是一种无状态的、无连接的、单向的应用层协议。它采用了请求（request）/响应(response)模型。<br>通信请求只能由客户端发起，服务端对请求做出应答处理。这就使得那些需要频繁更新实时数据的应用比较难受了，因为他老得去请求服务器，比如ajax轮询的方式，效率比较低，资源浪费率大；<br>那WebSocket就是为了解决这个问题诞生的</del><br>WebSocket 连接允许客户端和服务器之间进行全双工通信，以便任一方都可以通过建立的连接将数据推送到另一端。WebSocket 只需要建立一次连接，就可以一直保持连接状态。这相比于轮询方式的不停建立连接显然效率要大大提高。<br>好了，关于WebSocket的介绍就到这了，我说的也是借鉴了别人的博客，加以自己的一些理解，属于冰山一角，大家有兴趣可以去百度，去Google，在深入了解下。<br>接下来，咱还是说说怎么聊天吧<br>在这有个前提，因为我是用.net的技术来做的，对web服务器有一点要求，iis的版本必须在8.0以上才可以哦！8.0以下的版本不支持WebSocket协议<br>因为WebSocket是在客户端是HTML5提供支持的，所以绝大部分浏览器都可以做WebSocket的调试工作<br><img src="websocket_data.png" alt="websocket调试"><br>那我们的程序代码其实也很简单，客户端，只需要简单的几步操作就可以了（可以先大概了解下WebSocket的属性 <a href="http://www.runoob.com/html/html5-WebSocket.html" target="_blank" rel="noopener">http://www.runoob.com/html/html5-WebSocket.html</a> ），<br>我就直接上代码了昂</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><span class="line">&lt;html&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;</span><br><span class="line">    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0, maximum-scale=1.0&quot; /&gt;</span><br><span class="line">    &lt;title&gt;&lt;/title&gt;</span><br><span class="line">    &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;../../plugins/layui/css/layui.css&quot; /&gt;</span><br><span class="line">    &lt;script src=&quot;../../scripts/jquery/jquery-1.11.2.min.js&quot;&gt;&lt;/script&gt;</span><br><span class="line">    &lt;script&gt;</span><br><span class="line">        var ws;</span><br><span class="line">        $().ready(function () &#123;</span><br><span class="line">            $(&apos;#conn&apos;).click(function () &#123;</span><br><span class="line">                //打开WebSocket链接，和服务端去握手</span><br><span class="line">                ws = new WebSocket(&apos;ws://&apos; + window.location.hostname + &apos;:&apos; + window.location.port + &apos;/ymadmin/communication/communication_server.ashx?user=&apos; + $(&quot;#user&quot;).val());</span><br><span class="line">                $(&apos;#msg&apos;).append(&apos;&lt;p&gt;connecting...&lt;/p&gt;&apos;);</span><br><span class="line">                //握手成功</span><br><span class="line">                ws.onopen = function () &#123;</span><br><span class="line">                    $(&apos;#msg&apos;).append(&apos;&lt;p&gt;connecting...ok&lt;/p&gt;&apos;);</span><br><span class="line">                &#125;</span><br><span class="line">                //接收新消息</span><br><span class="line">                ws.onmessage = function (evt) &#123;</span><br><span class="line">                    $(&apos;#msg&apos;).append(&apos;&lt;p&gt;&apos; + $(&quot;#to&quot;).val() + &quot;:&quot; + evt.data + &apos;&lt;/p&gt;&apos;);</span><br><span class="line">                &#125;</span><br><span class="line">                //链接失败时</span><br><span class="line">                ws.onerror = function (evt) &#123;</span><br><span class="line">                    $(&apos;#msg&apos;).append(&apos;&lt;p&gt;error:&apos; + JSON.stringify(evt) + &apos;,connection is closed!&lt;/p&gt;&apos;);</span><br><span class="line">                &#125;</span><br><span class="line">                //链接关闭</span><br><span class="line">                ws.onclose = function () &#123;</span><br><span class="line">                    $(&apos;#msg&apos;).append(&apos;&lt;p&gt;connection has been closed!&lt;/p&gt;&apos;);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line"></span><br><span class="line">            $(&apos;#close&apos;).click(function () &#123;</span><br><span class="line">                ws.close();</span><br><span class="line">            &#125;);</span><br><span class="line">            //发送socket类型的数据到服务端</span><br><span class="line">            $(&apos;#send&apos;).click(function () &#123;</span><br><span class="line">                if (ws.readyState == WebSocket.OPEN) &#123;</span><br><span class="line">                    ws.send($(&quot;#to&quot;).val() + &quot;|&quot; + $(&apos;#content&apos;).val());</span><br><span class="line">                    $(&apos;#msg&apos;).append(&apos;&lt;p&gt;&apos; + &quot;me:&quot; + $(&apos;#content&apos;).val() + &apos;&lt;/p&gt;&apos;);</span><br><span class="line">                &#125;</span><br><span class="line">                else &#123;</span><br><span class="line">                    $(&apos;#tips&apos;).text(&apos;connection has been closed!&apos;);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line"></span><br><span class="line">        &#125;);</span><br><span class="line">    &lt;/script&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;div class=&quot;layui-container&quot;&gt;</span><br><span class="line">        &lt;div class=&quot;layui-row&quot;&gt;</span><br><span class="line">            &lt;div class=&quot;layui-col-md9&quot;&gt;</span><br><span class="line">                &lt;input id=&quot;conn&quot; type=&quot;button&quot; value=&quot;开启连接&quot; class=&quot;layui-btn&quot; /&gt;</span><br><span class="line">                &lt;input id=&quot;close&quot; type=&quot;button&quot; value=&quot;关闭链接&quot; class=&quot;layui-btn layui-btn-danger&quot;&gt;&lt;br /&gt;</span><br><span class="line">                发送者：&lt;input id=&quot;user&quot; type=&quot;text&quot; class=&quot;layui-input&quot; /&gt;</span><br><span class="line">                接收者：&lt;input id=&quot;to&quot; type=&quot;text&quot; class=&quot;layui-input&quot; /&gt;&lt;br /&gt;</span><br><span class="line">                &lt;span id=&quot;tips&quot;&gt;&lt;/span&gt;</span><br><span class="line">                发送内容：&lt;input id=&quot;content&quot; type=&quot;text&quot; class=&quot;layui-input&quot; /&gt;</span><br><span class="line">                &lt;input id=&quot;send&quot; type=&quot;button&quot; value=&quot;发送&quot; class=&quot;layui-btn layui-btn-normal&quot; /&gt;&lt;br /&gt;</span><br><span class="line">            &lt;/div&gt;</span><br><span class="line">            &lt;br /&gt;</span><br><span class="line">        &lt;/div&gt;</span><br><span class="line">        &lt;div class=&quot;layui-row&quot; id=&quot;msg&quot;&gt;</span><br><span class="line">            聊天记录</span><br><span class="line">        &lt;/div&gt;</span><br><span class="line">    &lt;/div&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>

<p>服务端代码我是用.net的一般处理程序（ashx文件）来做的，微软官方的解释是这种方式效率比较高，用webapi的方式也可以，我试了试，还没试成功。。。，就先分享这种方式吧</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br></pre></td><td class="code"><pre><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// 离线消息</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">public class MessageInfo</span><br><span class="line">&#123;</span><br><span class="line">    public MessageInfo(DateTime _MsgTime, ArraySegment&lt;byte&gt; _MsgContent)</span><br><span class="line">    &#123;</span><br><span class="line">        MsgTime = _MsgTime;</span><br><span class="line">        MsgContent = _MsgContent;</span><br><span class="line">    &#125;</span><br><span class="line">    /// &lt;summary&gt;</span><br><span class="line">    /// 消息时间</span><br><span class="line">    /// &lt;/summary&gt;</span><br><span class="line">    public DateTime MsgTime &#123; get; set; &#125;</span><br><span class="line">    /// &lt;summary&gt;</span><br><span class="line">    /// 消息内容</span><br><span class="line">    /// &lt;/summary&gt;</span><br><span class="line">    public ArraySegment&lt;byte&gt; MsgContent &#123; get; set; &#125;</span><br><span class="line">&#125;</span><br><span class="line">/// &lt;summary&gt;</span><br><span class="line">/// communication_server 的摘要说明</span><br><span class="line">/// &lt;/summary&gt;</span><br><span class="line">public class communication_server : IHttpHandler</span><br><span class="line">&#123;</span><br><span class="line">    private static Dictionary&lt;string, WebSocket&gt; CONNECT_POOL = new Dictionary&lt;string, WebSocket&gt;();//用户连接池</span><br><span class="line">    private static Dictionary&lt;string, List&lt;MessageInfo&gt;&gt; MESSAGE_POOL = new Dictionary&lt;string, List&lt;MessageInfo&gt;&gt;();//离线消息池</span><br><span class="line"></span><br><span class="line">    public void ProcessRequest(HttpContext context)</span><br><span class="line">    &#123;</span><br><span class="line">        if (context.IsWebSocketRequest)</span><br><span class="line">        &#123;</span><br><span class="line">            context.AcceptWebSocketRequest(ProcessChat);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private async Task ProcessChat(AspNetWebSocketContext context)</span><br><span class="line">    &#123;</span><br><span class="line">        WebSocket socket = context.WebSocket;</span><br><span class="line">        string user = context.QueryString[&quot;user&quot;].ToString();</span><br><span class="line"></span><br><span class="line">        try</span><br><span class="line">        &#123;</span><br><span class="line">            #region 用户添加连接池</span><br><span class="line">            //第一次open时，添加到连接池中</span><br><span class="line">            if (!CONNECT_POOL.ContainsKey(user))</span><br><span class="line">                CONNECT_POOL.Add(user, socket);//不存在，添加</span><br><span class="line">            else</span><br><span class="line">                if (socket != CONNECT_POOL[user])//当前对象不一致，更新</span><br><span class="line">                    CONNECT_POOL[user] = socket;</span><br><span class="line">            #endregion</span><br><span class="line"></span><br><span class="line">            #region 离线消息处理</span><br><span class="line">            if (MESSAGE_POOL.ContainsKey(user))</span><br><span class="line">            &#123;</span><br><span class="line">                List&lt;MessageInfo&gt; msgs = MESSAGE_POOL[user];</span><br><span class="line">                foreach (MessageInfo item in msgs)</span><br><span class="line">                &#123;</span><br><span class="line">                    await socket.SendAsync(item.MsgContent, WebSocketMessageType.Text, true, CancellationToken.None);</span><br><span class="line">                &#125;</span><br><span class="line">                MESSAGE_POOL.Remove(user);//移除离线消息</span><br><span class="line">            &#125;</span><br><span class="line">            #endregion</span><br><span class="line"></span><br><span class="line">            string descUser = string.Empty;//目的用户</span><br><span class="line">            while (true)</span><br><span class="line">            &#123;</span><br><span class="line">                if (socket.State == WebSocketState.Open)</span><br><span class="line">                &#123;</span><br><span class="line">                    ArraySegment&lt;byte&gt; buffer = new ArraySegment&lt;byte&gt;(new byte[2048]);</span><br><span class="line">                    WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);</span><br><span class="line"></span><br><span class="line">                    #region 消息处理（字符截取、消息转发）</span><br><span class="line">                    try</span><br><span class="line">                    &#123;</span><br><span class="line">                        #region 关闭Socket处理，删除连接池</span><br><span class="line">                        if (socket.State != WebSocketState.Open)//连接关闭</span><br><span class="line">                        &#123;</span><br><span class="line">                            if (CONNECT_POOL.ContainsKey(user)) CONNECT_POOL.Remove(user);//删除连接池</span><br><span class="line">                            break;</span><br><span class="line">                        &#125;</span><br><span class="line">                        #endregion</span><br><span class="line"></span><br><span class="line">                        string userMsg = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);//发送过来的消息</span><br><span class="line">                        string[] msgList = userMsg.Split(&apos;|&apos;);</span><br><span class="line">                        if (msgList.Length == 2)</span><br><span class="line">                        &#123;</span><br><span class="line">                            if (msgList[0].Trim().Length &gt; 0)</span><br><span class="line">                                descUser = msgList[0].Trim();//记录消息目的用户</span><br><span class="line">                            buffer = new ArraySegment&lt;byte&gt;(Encoding.UTF8.GetBytes(msgList[1]));</span><br><span class="line">                        &#125;</span><br><span class="line">                        else</span><br><span class="line">                            buffer = new ArraySegment&lt;byte&gt;(Encoding.UTF8.GetBytes(userMsg));</span><br><span class="line"></span><br><span class="line">                        if (CONNECT_POOL.ContainsKey(descUser))//判断客户端是否在线</span><br><span class="line">                        &#123;</span><br><span class="line">                            WebSocket destSocket = CONNECT_POOL[descUser];//目的客户端</span><br><span class="line">                            if (destSocket != null &amp;&amp; destSocket.State == WebSocketState.Open)</span><br><span class="line">                                await destSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);</span><br><span class="line">                        &#125;</span><br><span class="line">                        else</span><br><span class="line">                        &#123;</span><br><span class="line">                            await Task.Run(() =&gt;</span><br><span class="line">                            &#123;</span><br><span class="line">                                if (!MESSAGE_POOL.ContainsKey(descUser))//将用户添加至离线消息池中</span><br><span class="line">                                    MESSAGE_POOL.Add(descUser, new List&lt;MessageInfo&gt;());</span><br><span class="line">                                MESSAGE_POOL[descUser].Add(new MessageInfo(DateTime.Now, buffer));//添加离线消息</span><br><span class="line">                            &#125;);</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                    catch (Exception exs)</span><br><span class="line">                    &#123;</span><br><span class="line">                        //消息转发异常处理，本次消息忽略 继续监听接下来的消息</span><br><span class="line">                    &#125;</span><br><span class="line">                    #endregion</span><br><span class="line">                &#125;</span><br><span class="line">                else</span><br><span class="line">                &#123;</span><br><span class="line">                    break;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;//while end</span><br><span class="line">        &#125;</span><br><span class="line">        catch (Exception ex)</span><br><span class="line">        &#123;</span><br><span class="line">            //整体异常处理</span><br><span class="line">            if (CONNECT_POOL.ContainsKey(user)) CONNECT_POOL.Remove(user);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public bool IsReusable</span><br><span class="line">    &#123;</span><br><span class="line">        get</span><br><span class="line">        &#123;</span><br><span class="line">            return false;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实现之后的效果如下<br><img src="connection.png" alt="效果0"><br><img src="communication1.png" alt="效果1"><br><img src="communication2.png" alt="效果2"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/hexo/tags/经验分享/" rel="tag"># 经验分享</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/hexo/2018/10/23/实则害了自己/" rel="next" title="实则害了自己">
                <i class="fa fa-chevron-left"></i> 实则害了自己
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/hexo/2018/10/31/亿万人的武侠梦/" rel="prev" title="亿万人的武侠梦">
                亿万人的武侠梦 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_inline_share_toolbox">
  <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5bbb2338b87602f0" async="async"></script>
</div>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zOTA1My8xNTU4MA"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Tony</p>
              <p class="site-description motion-element" itemprop="description">学习总结</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/hexo/archives/">
              
                  <span class="site-state-item-count">58</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/hexo/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/hexo/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/hexo/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/hexo/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/hexo/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/hexo/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/hexo/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

</body>
</html>
